#include <sys/ipc.h>
#include <sys/shm.h>
#include <iostream>
#include <cstring>
#include <string>
#include <cerrno>
#include <cassert>
#include <unistd.h>
#include <fcntl.h>
#define DROJID 0x66C
#define PATHNAME "." // 进程名
#define Size 4096

std::string to_hex(int x) // 十进制转十六进制
{
    char buf[64];
    snprintf(buf, sizeof(buf), "0x%x", x);
    return buf;
}

key_t getkey()
{
    key_t key = ftok(PATHNAME, DROJID);
    if (key == -1)
    {
        // 获取key失败
        std::cerr << "getkey fail !!! errno:" << errno << "|" << strerror(errno) << std::endl;
        exit(1);
    }
    return key;
}

int shmhelper(key_t key, size_t size, int shmflag) // 简化创建共享内存流程
{
    int shmid = shmget(key, size, shmflag);
    if (shmid == -1)
    {
        std::cerr << "create shm fail !!! errno:" << errno << "|" << strerror(errno) << std::endl;
        exit(2);
    }
    return shmid;
}

int createshm(key_t key, size_t size) // 创建共享空间
{
    return shmhelper(key, size, IPC_CREAT | IPC_EXCL | 0666);
}

int getshm(key_t key, size_t size) // 操控共享空间
{
    return shmhelper(key, size, IPC_CREAT);
}

// int ctlshm(int shmid,int cmd,shmid_ds *buf) //可以直接使用shmctl
// {
//     int end = shmctl(shmid,cmd,buf);
//     return end;
// }



